const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const dietRecordSchema = new Schema(
  {
    userId: {
      type: Schema.Types.ObjectId,
      ref: 'User', // 假设您的用户模型名为 'User'
      required: true,
      index: true,
    },
    mealType: {
      type: String,
      enum: ['早餐', '午餐', '晚餐', '加餐'],
      required: true,
    },
    date: {
      type: Date,
      required: true,
      index: true,
    },
    time: {
      type: String, // 格式如 HH:mm
      required: true,
    },
    foods: [
      {
        food: {
          _id: {
            type: Schema.Types.ObjectId,
            ref: 'Food', // 假设您的食物模型名为 'Food'
            required: true,
          },
          name: {
            type: String,
            required: true,
          },
          image: String,
          unit: String, // 食物本身的基础单位，如 克、个
          calories: Number, // 食物本身每单位的热量
        },
        amount: {
          type: Number,
          required: true,
          min: 0,
        },
        unit: {
          type: String, // 用户实际食用的单位，可能与食物基础单位不同
          required: true,
        },
        calories: {
          // 这条记录中该食物的实际摄入热量
          type: Number,
          required: true,
          min: 0,
        },
        nutrition: {
          protein: { type: Number, default: 0 },
          fat: { type: Number, default: 0 },
          carbohydrate: { type: Number, default: 0 },
          // 可以根据需要扩展其他营养素，例如：
          // fiber: { type: Number, default: 0 },
          // sugar: { type: Number, default: 0 },
          // sodium: { type: Number, default: 0 },
        },
      },
    ],
    totalCalories: {
      type: Number,
      required: true,
      default: 0,
    },
    totalNutrition: {
      protein: { type: Number, default: 0 },
      fat: { type: Number, default: 0 },
      carbohydrate: { type: Number, default: 0 },
      // 与 foods.nutrition 保持一致
    },
    note: {
      type: String,
      trim: true,
    },
    images: [
      {
        type: String,
        trim: true,
      },
    ],
    isDeleted: {
      type: Boolean,
      default: false,
      index: true,
    },
  },
  {
    timestamps: true, // 会自动添加 createdAt 和 updatedAt 字段
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
    collection: 'diet_records' // 明确指定集合名称
  }
);

// 中间件：在保存前自动计算总热量和总营养素
dietRecordSchema.pre('save', function (next) {
  if (this.isModified('foods') || this.isNew) {
    let newTotalCalories = 0;
    const newTotalNutrition = {
      protein: 0,
      fat: 0,
      carbohydrate: 0,
    };
    this.foods.forEach(item => {
      newTotalCalories += item.calories || 0;
      newTotalNutrition.protein += item.nutrition?.protein || 0;
      newTotalNutrition.fat += item.nutrition?.fat || 0;
      newTotalNutrition.carbohydrate += item.nutrition?.carbohydrate || 0;
    });
    this.totalCalories = newTotalCalories;
    this.totalNutrition = newTotalNutrition;
  }
  next();
});

/**
 * @typedef DietRecord
 */
const DietRecord = mongoose.model('DietRecord', dietRecordSchema);

module.exports = DietRecord; 